package com.sunsharing.flow.eventman;

import com.sunsharing.common.anno.AnoClassCretator;
import com.sunsharing.flow.event.ApplicationEvent;
import org.apache.log4j.Logger;

import java.util.Iterator;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: criss
 * Date: 13-5-4
 * Time: 下午8:12
 * To change this template use File | Settings | File Templates.
 */
public class EventManager {
    /**日志**/
    protected Logger logger = Logger.getLogger(this.getClass());

    /**实例**/
    private static EventManager manager = new EventManager();

    /**事件传播器**/
    private EventMulticaster eventMulticaster;

    /**注册事件获取HQL**/
    private final static String FIND_ALL_LISTENERS =
            "Select listener From ListenerDescription as listener";

    private EventManager() {
        eventMulticaster = new ApplicationEventMulticaster();
        //注册监听器
        registerListeners();

    }

    /**
     * 功能描述:
     *     获得事件管理器的单实例
     * @return EventManager
     */
    public static EventManager getInstance() {
        return manager;
    }

    /**
     * 功能描述:
     *    初始化
     */
    protected void registerListeners() {

        ApplicationListener app =
                (ApplicationListener)AnoClassCretator.getInstance().
                        createObject(ApplicationListener.class,"FlowEndLisener");
        addApplicationListener(GlobalObject.obj,app);
        //获得所有的监听器
//        List list = PersistenceService.find(FIND_ALL_LISTENERS);
//        if(logger.isDebugEnabled()) {
//            logger.debug("注册的监听器总共:" + list.size() + "个");
//        }
//        Iterator itor = list.iterator();
//        while(itor.hasNext()) {
//            //获得监听器描述
//            ListenerDescription listenerDesc = (ListenerDescription)itor.next();
//            ApplicationEvent event =listenerDesc.getEvent();
//            if(logger.isDebugEnabled()) {
//                logger.debug("注册的事件类型:" + event.getClass().getName());
//            }
//            //加入监听器
//            addApplicationListener(event,listenerDesc);
//        }
    }

    /**
     * 功能描述:
     *     发布事件
     * @param event ApplicationEvent
     */
    public void multicastEvent(ApplicationEvent event) {
        eventMulticaster.multicastEvent(event);
    }


    /**
     * 功能描述:
     *    增加监听器
     * @param
     * @param
     */
    public synchronized void addApplicationListener(Object obj,ApplicationListener listenerDesc){
        eventMulticaster.addApplicationListener(obj,listenerDesc);
    }


    /**
     * 功能描述:
     *    移除监听器
     * @param event ApplicationEvent
     * @param
     */
    public synchronized void removeApplicationListener(Object event,ApplicationListener listenerDesc){
        eventMulticaster.removeApplicationListener(event,listenerDesc);
    }


    /**
     * 功能描述:
     *    移除所有的监听器
     */
    public synchronized void removeAllListeners() {
        eventMulticaster.removeAllListeners();
    }



}
